﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using Jillzhang.GifUtility;
using Silverlight.Samples;
using System.Windows.Media.Imaging;

namespace ArmoryBrowser
{
    public static class GifLoadingBehavior
    {


        public static String GetImageUrl(DependencyObject obj)
        {
            return (String)obj.GetValue(ImageUrlProperty);
        }

        public static void SetImageUrl(DependencyObject obj, String value)
        {
            obj.SetValue(ImageUrlProperty, value);
        }

        // Using a DependencyProperty as the backing store for ImageUrl.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ImageUrlProperty =
            DependencyProperty.RegisterAttached("ImageUrl", typeof(String), typeof(GifLoadingBehavior), new PropertyMetadata(ImageUrlPropertyChanged));

        private static void ImageUrlPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
        {
            Image element = target as Image;
            Uri imageuri = new Uri((String)args.NewValue);
            WebClient client = new WebClient();
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(delegate(object sender, OpenReadCompletedEventArgs e)
            {
                using (Stream str = e.Result)
                {
                    GifImage img = GIFDecoder.Decode(str);
                    BitmapImage b = new BitmapImage();
                    b.SetSource(img.Frames[0].Image.GetStream());
                    element.Source = b;
                }
            });
            client.OpenReadAsync(imageuri);
        }
    }
}
